import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/car_info_list_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_details_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/return_booking_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/pages/common/LoadBuilder.dart';
import 'package:xiongan_app_yy/pages/common/TextFieldItem.dart';
import 'package:xiongan_app_yy/provider/erp_info.dart';
import 'package:xiongan_app_yy/utils/license_plate_utils.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/dropdownmenu.dart';
import 'package:xiongan_app_yy/widgets/comm/input_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/scan_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_card_widget_new.dart';
import 'package:xiongan_app_yy/widgets/comm/text_exhibition_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/time_card_widget.dart';
import 'package:xiongan_app_yy/widgets/inv_list_page_new_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/notification/image_notification.dart';
import 'package:xiongan_app_yy/widgets/notification/time_notification.dart';

//退货预约-新建
class ReturnBookingNew extends StatefulWidget {
  final Map<String, dynamic> args;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ReturnBookingNewState();
  }

  ReturnBookingNew(this.args);
}

class ReturnBookingNewState extends State<ReturnBookingNew> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  bool visibility = true; //false不隐藏，true隐藏
  bool visibilityLoad = true; //加载循环进度条 false隐藏进度条
  bool editNo = true; //单号是否可编辑
  String erpno;
  String time;
  String libraryTime;
  List<String> imageList;
  List<File> imageFileList;
  int index;
  String data;
  String orgId;
  String libraryProject;
  String libraryProjectName;
  Color bgColor = Colors.white;
  TextEditingController reasonStr = new TextEditingController();
  List<dynamic> libraryProjectData = new List();
  String proText = "浙";
  int textNum = 0;
  List<String> numberList = new List();
  TextEditingController controller = TextEditingController();
  TextEditingController controller0 = TextEditingController();
  TextEditingController controller1 = TextEditingController();
  TextEditingController controller2 = TextEditingController();
  TextEditingController controller3 = TextEditingController();
  List<CarInfoListItem> datas = [];
  String projectName = "";

  @override
  void initState() {
    super.initState();
    if (widget.args != null) {
      InvListDetailsEntity bean = widget.args["bean"];
      controller.text = bean.datas.warehouseoutno;
      controller0.text = bean.datas.driver;
      controller1.text = bean.datas.phone;
      orgId = bean.datas.id;
      visibilityLoad = true;
      bgColor = Colors.black26;
      datas.addAll(bean.datas.carList);
      getData();
    }
    getLibraryProject();
  }

  @override
  Widget build(BuildContext context) {
    controller.selection = TextSelection.fromPosition(TextPosition(
        affinity: TextAffinity.downstream, offset: controller.text.length));
    textNum = 0;
    if (Provider.of<ErpInfo>(context).rbean != null) {
      for (int i1 = 0;
          i1 < Provider.of<ErpInfo>(context).rbean.outOrderDetailList.length;
          i1++) {
        textNum = Provider.of<ErpInfo>(context)
                .rbean
                .outOrderDetailList[i1]
                .realquantity +
            textNum;
      }
    }
    return NotificationListener(
        onNotification: (notification) {
          print(notification.runtimeType);
          switch (notification.runtimeType) {
            case ImageNotification:
              if (notification.msg == "String") {
                imageList = notification.list;
                print("图片list$imageList");
              } else {
                imageFileList = notification.fileList;
                print("图片file$imageFileList");
              }
              break;
            case TimeNotification:
              if (notification.index == 0) {
                libraryTime = notification.msg;
                print(libraryTime);
              } else {
                time = notification.msg;
              }
              break;
          }
          return false;
        },
        child: Scaffold(
          key: scaffoldKey,
          appBar: AppBar(
            leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
            title: Text(
              "新建工程结余退库预约",
              style: TextStyle(fontSize: 18),
            ),
            elevation: 0,
            centerTitle: true,
            backgroundColor: Color(0XFF00A5F1),
          ),
          body: LoadBuilder(
              visibility: visibilityLoad,
              bgColor: bgColor,
              builder: Column(
                children: <Widget>[
                  Expanded(
                      child: ListView(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          InputCardWidget(
                            suffixIcon: ScanWidget(
                              clickCallback: (value) {
                                setState(() {
                                  controller.text = value.trim();
                                });
                                getData();
                              },
                            ),
                            enabled: editNo,
                            hintText: "输入或扫描单号回车查询",
                            title: "原出库单号:",
                            contro: controller,
                            enterListen: (value) {
                              if (value.length > 0) {
                                setState(() {
                                  visibilityLoad = true;
                                  bgColor = Colors.black26;
                                });
                                getData();
                              }
                            },
                            textAction: TextInputAction.done,
                          ),
                          TextExhibitionCardWidget(
                              position: CrossAxisAlignment.start,
                              exhibitionTextColor: Color(0xFF323232),
                              title: "项目名称:",
                              exhibitionText: projectName,
                              distance: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 15, top: 15),
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          TextCardWidgetNew(
                              onPressed: () {
                                //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                                Navigator.pushNamed(context, "/carSelect",
                                    arguments: {"datas": datas}).then((value) {
                                  if (value != null) {
                                    setState(() {
                                      datas = value;
                                    });
                                  }
                                });
                              },
                              title: "车辆信息:",
                              textNum: false,
                              details: false,
                              num: "${datas.length}辆",
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(left: 16),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                      bottom: BorderSide(
                                          width: 1, color: Color(0xffefefef)))),
                              child: new Row(
                                children: <Widget>[
                                  Container(
                                    child: Text("利库项目:",
                                        style: TextStyle(fontSize: 16)),
                                    padding: EdgeInsets.only(
                                      top: 15,
                                      bottom: 15,
                                    ),
                                  ),
                                  Expanded(
                                    child: DropDownMenu(
                                      //border: Border(bottom: BorderSide(width: 1, color: Color(0xffefefef))),
                                      border: Border.fromBorderSide(
                                          BorderSide.none),
                                      hitText: "请选择利库项目",
                                      radius: BorderRadius.zero,
                                      margin: EdgeInsets.all(0),
                                      datas: libraryProjectData,
                                      keyItem: {"id": "projecttheme"},
                                      value: libraryProject,
                                      onChange: (v) {
                                        setState(() {
                                          libraryProject = v["value"];
                                          libraryProjectName =
                                              v["item"]["projecttheme"];
                                        });
                                      },
                                    ),
                                  )
                                ],
                              )),
                          TimeCardWidget(
                              scaffoldKey: scaffoldKey,
                              index: 0,
                              hintText: "请选择利库时间",
                              title: "利库时间:"),
                          Offstage(
                              offstage: visibility,
                              child: TextCardWidgetNew(
                                  onPressed: () {
                                    Navigator.pushNamed(
                                        context, "/storageDetails", arguments: {
                                      "type": "push",
                                      "title": "结余退库物资明细"
                                    });
                                    /* Navigator.pushNamed(context, "/return_storage_details");*/
                                  },
                                  textNum: false,
                                  num: textNum.toString(),
                                  title: "物资明细:",
                                  border:
                                      Border.fromBorderSide(BorderSide.none))),
                          TimeCardWidget(
                              custom: true,
                              scaffoldKey: scaffoldKey,
                              index: 1,
                              hintText: "请选择到货时间",
                              title: "预计到货时间:",
                              margin: EdgeInsets.only(top: 20, bottom: 20),
                              border: Border.fromBorderSide(BorderSide.none)),
                          Container(
                              color: Colors.white,
                              child: TextFieldItem(
                                scan: false,
                                height: 130,
                                hintText: "输入退库原因:",
                                mLine: 8,
                                textEditingController: reasonStr,
                                mar: EdgeInsets.all(10),
                                contentPad: EdgeInsets.all(5),
                              )),
                        ],
                      ),
                      UploadImgWidget(),
                    ],
                  )),
                  Container(
                    width: double.infinity,
                    height: 48,
                    child: FlatButton(
                      color: Color(0XFF00A5F1),
                      child: Text(
                        "提交",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: upData,
                    ),
                  )
                ],
              )),
        ));
  }

  void upData() {
    if (erpno != null && erpno.length > 0) {
      for (int i = 0; i < datas.length; i++) {
        if (datas[i].driver != null && datas[i].driver.length > 0) {
          if (datas[i].phone != null && datas[i].phone.length > 0) {
            if (datas[i].carno != null &&
                datas[i].carno.length > 0 &&
                LicensePlateUtils.isLicensePlate(datas[i].carno)) {
              if (i + 1 == datas.length) {
                if (libraryProjectName != null &&
                    libraryProjectName.length > 0) {
                  if (libraryTime != null && libraryTime.length > 0) {
                    if (time != null && time.length > 0) {
                      setState(() {
                        visibilityLoad = true;
                      });
                      if (imageList == null && imageFileList == null) {
                        //没有图
                        Map<String, dynamic> data =
                            Provider.of<ErpInfo>(context).rbean.toJson();
                        InternetAPI.getInstance().post(
                          "OMS/MiBackWarehouseTask/AddMiBackWarehouseTask",
                          (data) {
                            print(data.toString());
                            //Navigator.popAndPushNamed(context, "/success",result: "wu");
                            if (data == true) {
                              Navigator.pop(context, "ok");
                              TostUtil.showToast("提交成功");
                            }
                          },
                          errorCallBack: (err) {
                            setState(() {
                              visibilityLoad = false;
                            });
                          },
                          params: {
                            "operaterUserName": DataSingleton().Data.username,
                            "operaterUserId": DataSingleton().Data.id,
                            "tenantId": DataSingleton().Data.tenantId,
                            "creationTime":
                                DateTime.now().toString().substring(0, 19),
                            "carno": controller2.text,
                            "applytime": time.substring(0, 19),
                            "warehouseoutno": erpno,
                            "orgId": orgId,
                            "driver": controller0.text,
                            "phone": controller1.text,
                            "projectname": projectName,
                            "Rikutime ": libraryTime,
                            "Rikuprojectid": libraryProject,
                            "Rikuproject": libraryProjectName,
                            "remark": reasonStr.text ?? "",
                            "detailList": data["outOrderDetailList"],
                            "warehouseid": DataSingleton().warehouseChoice.id,
                            "carList": datas,
                          },
                        );
                      } else {
                        //有图
                        if (imageList.length == imageFileList.length) {
                          //图上传完成
                          Map<String, dynamic> data =
                              Provider.of<ErpInfo>(context).rbean.toJson();
                          List<InvListDatasImglist> img = new List();
                          for (int i = 0; i < imageList.length; i++) {
                            img.add(InvListDatasImglist(
                                imgstr: imageList.elementAt(i)));
                          }
                          InternetAPI.getInstance().post(
                            "OMS/MiBackWarehouseTask/AddMiBackWarehouseTask",
                            (data) {
                              if (data == true) {
                                Navigator.pop(context, "ok");
                                TostUtil.showToast("提交成功");
                              }
                            },
                            errorCallBack: (err) {
                              setState(() {
                                visibilityLoad = false;
                              });
                            },
                            params: {
                              "operaterUserName": DataSingleton().Data.username,
                              "operaterUserId": DataSingleton().Data.id,
                              "tenantId": DataSingleton().Data.tenantId,
                              "creationTime":
                                  DateTime.now().toString().substring(0, 19),
                              "carno": controller2.text,
                              "applytime": time.substring(0, 19),
                              "warehouseoutno": erpno,
                              "driver": controller0.text,
                              "phone": controller1.text,
                              "projectname": projectName,
                              "Rikutime ": libraryTime,
                              "Rikuprojectid": libraryProject,
                              "Rikuproject": libraryProjectName,
                              "detailList": data["outOrderDetailList"],
                              "imgList": img,
                              "remark": reasonStr.text ?? "",
                              "warehouseid": DataSingleton().warehouseChoice.id,
                              "carList": datas,
                            },
                          );
                        } else {
                          TostUtil.showToast("大图上传中，请稍后");
                        }
                      }
                    } else {
                      TostUtil.showToast("请选择到货时间");
                    }
                  } else {
                    TostUtil.showToast("请选择利库时间");
                  }
                } else {
                  TostUtil.showToast("请选择利库项目");
                }
              }
            } else {
              TostUtil.showToast("请填写第${i + 1}位正确的车牌号");
              break;
            }
          } else {
            TostUtil.showToast("请填写第${i + 1}位司机手机号");
            break;
          }
        } else {
          TostUtil.showToast("请填写第${i + 1}位司机姓名");
          break;
        }
      }
    } else {
      TostUtil.showToast("请输入正确的单号");
    }
  }

  void _upData() {
    if (erpno != null && erpno.length > 0) {
      if (controller0.text != null && controller0.text.length > 0) {
        if (controller1.text != null && controller1.text.length > 0) {
          if (controller2.text != null && controller2.text.length > 0) {
            if (LicensePlateUtils.isLicensePlate(proText + controller2.text)) {
              if (libraryProjectName != null && libraryProjectName.length > 0) {
                if (libraryTime != null && libraryTime.length > 0) {
                  if (time != null && time.length > 0) {
                    setState(() {
                      visibilityLoad = true;
                    });
                    if (imageList == null && imageFileList == null) {
                      //没有图
                      Map<String, dynamic> data =
                          Provider.of<ErpInfo>(context).rbean.toJson();
                      InternetAPI.getInstance().post(
                        "OMS/MiBackWarehouseTask/AddMiBackWarehouseTask",
                        (data) {
                          if (data == true) {
                            Navigator.pop(context, "ok");
                            TostUtil.showToast("提交成功");
                          }
                        },
                        errorCallBack: (err) {
                          setState(() {
                            visibilityLoad = false;
                          });
                        },
                        params: {
                          "operaterUserName": DataSingleton().Data.username,
                          "operaterUserId": DataSingleton().Data.id,
                          "tenantId": DataSingleton().Data.tenantId,
                          "creationTime":
                              DateTime.now().toString().substring(0, 19),
                          "carno": controller2.text,
                          "applytime": time.substring(0, 19),
                          "warehouseoutno": erpno,
                          "orgId": orgId,
                          "driver": controller0.text,
                          "phone": controller1.text,
                          "projectname": projectName,
                          "Rikutime ": libraryTime,
                          "Rikuprojectid": libraryProject,
                          "Rikuproject": libraryProjectName,
                          "remark": reasonStr.text ?? "",
                          "detailList": data["outOrderDetailList"],
                          "warehouseid": DataSingleton().warehouseChoice.id,
                          "carList": datas,
                        },
                      );
                    } else {
                      //有图
                      if (imageList.length == imageFileList.length) {
                        //图上传完成
                        Map<String, dynamic> data =
                            Provider.of<ErpInfo>(context).rbean.toJson();
                        List<InvListDatasImglist> img = new List();
                        for (int i = 0; i < imageList.length; i++) {
                          img.add(InvListDatasImglist(
                              imgstr: imageList.elementAt(i)));
                        }
                        InternetAPI.getInstance().post(
                          "OMS/MiBackWarehouseTask/AddMiBackWarehouseTask",
                          (data) {
                            print(data.toString());
                            //Navigator.popAndPushNamed(context, "/success",result: "wu");
                            if (data == true) {
                              Navigator.pop(context, "ok");
                              TostUtil.showToast("提交成功");
                            }
                          },
                          errorCallBack: (err) {
                            setState(() {
                              visibilityLoad = false;
                            });
                          },
                          params: {
                            "operaterUserName": DataSingleton().Data.username,
                            "operaterUserId": DataSingleton().Data.id,
                            "tenantId": DataSingleton().Data.tenantId,
                            "creationTime":
                                DateTime.now().toString().substring(0, 19),
                            "carno": controller2.text,
                            "applytime": time.substring(0, 19),
                            "warehouseoutno": erpno,
                            "driver": controller0.text,
                            "phone": controller1.text,
                            "projectname": projectName,
                            "Rikutime ": libraryTime,
                            "Rikuprojectid": libraryProject,
                            "Rikuproject": libraryProjectName,
                            "detailList": data["outOrderDetailList"],
                            "imgList": img,
                            "remark": reasonStr.text ?? "",
                            "warehouseid": DataSingleton().warehouseChoice.id,
                            "carList": datas,
                          },
                        );
                      } else {
                        TostUtil.showToast("大图上传中，请稍后");
                      }
                    }
                  } else {
                    TostUtil.showToast("请选择到货时间");
                  }
                } else {
                  TostUtil.showToast("请选择利库时间");
                }
              } else {
                TostUtil.showToast("请选择利库项目");
              }
            } else {
              TostUtil.showToast("请填写正确车牌");
            }
          } else {
            TostUtil.showToast("请填写车牌号");
          }
        } else {
          TostUtil.showToast("请填写司机手机号");
        }
      } else {
        TostUtil.showToast("请填写司机姓名");
      }
    } else {
      TostUtil.showToast("请输入正确的单号");
    }
  }

  void getData() {
    InternetAPI.getInstance().post(
      "WMS/MiWarehouseOutOrder/GetOutOrderInfoByOrderno",
      (data) {
        ReturnBookingEntity bean = ReturnBookingEntity.fromJson(data);
        Provider.of<ErpInfo>(context).setRbean(bean);
        setState(() {
          erpno = controller.text;
          editNo = false;
          projectName = bean.projectname;
          visibility = false;
          visibilityLoad = false;
        });
      },
      errorCallBack: (err) {
        setState(() {
          visibilityLoad = false;
        });
      },
      params: {
        'operaterUserId': DataSingleton().Data.id,
        'orderno': controller.text,
        'tenantId': DataSingleton().Data.tenantId,
        'Warehouseid': DataSingleton().warehouseChoice.id,
      },
      options: new Options(
          contentType: ContentType.parse("application/x-www-form-urlencoded")),
    );
  }

  _changeText(text) {
    proText = text;
  }

  void getLibraryProject() {
    InternetAPI.getInstance().get("WProject/MiProject/GetAllMiProject", (data) {
      print(data);
      setState(() {
        libraryProjectData = data;
        visibilityLoad = false;
      });
    }, errorCallBack: (err) {
      setState(() {
        visibilityLoad = false;
      });
    }, params: {
      'operaterUserId': DataSingleton().Data.id,
      'tenantId': DataSingleton().Data.tenantId,
      'Warehouseid': DataSingleton().warehouseChoice.id,
      'pageNo': -1
    });
  }
}
